<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/10/9
 * Time: 下午2:47
 */

namespace Lm\Controllers;


use Admin\Models\crm\XhcustInfo;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;
use Admin\Models\lm\XHLmCar;
use Admin\Models\lm\XHLmUseCar;
use Phalcon\Exception;

class CarController extends ControllerBase
{
    public function indexAction()
    {
        echo 'car';
    }


    private static $enums = [
        'iState' => [0 => '新建', 1 => '部门审批', 2 => '办公室审批', 3 => '审批通过', 4 => "撤回"]
    ];

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }

    /**
     * 车辆列表
     *
     * created by dale 2017/10/9
     */
    public function carListAction()
    {
        UserPower::checkUserPower('Lm_Car_CarList') or die('缺少权限');
        Assets::easyUI();
        Assets::importJs('js/car/carList.js');
        Assets::sweetAlert2();
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('car/carList');
        Template::exists('carList', 'list') or die(Main::showMessageModal('carList 配置文件不存在，请先创建！', 109106002));
        $listButton = [];
        if (UserPower::checkUserPower('Lm_Car_CarList_Add')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Lm_Car_CarList_Edit')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_Edit', 'text' => '编辑', 'icon' => 'fa-pencil');
        }
        if (UserPower::checkUserPower('Lm_Car_CarList_Del')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
//        if(UserPower::checkUserPower('Lm_Car_CarList_Confirm')){
//            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_startUse', 'text' => '取车确认', 'icon' => 'fa fa-key');
//            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_endUse', 'text' => '还车确认', 'icon' => 'fa fa-key');
//        }

        $this->view->setVars(array(
            'carList' => Template::createList('carList', 'carList', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),
            ]),
        ));
    }

    /**
     * 车辆表单
     *
     * created by dale 2017/10/9
     */
    public function carFormAction()
    {
        $id    = $this->request->getQuery('iCarId', 'string');
        $check = '';
        if ($id) {
            $car = XHLmCar::findFirst([
                'conditions' => 'bDelete=0 AND iCarId=:iCarId:',
                'bind'       => ['iCarId' => $id],
            ])->toArray();
            if (!UserPower::checkUserPower('Lm_Car_CarList_Edit')) {
                $check = '<script>parent.$(\'#bt_modal_confirm\').hide();</script>';
            } else {
                if (Main::getLoginUserInfo('logonName') != 'admin' &&
                    Main::getLoginUserInfo('userId') != $car['iCreateUserId']) {
                    $check = '<script>parent.$(\'#bt_modal_confirm\').hide();</script>';
                }
            }
            $carInfo = json_encode($car);
        } else {
            $carInfo = '1';
        }
        $this->view->pick('car/carForm');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/car/carForm.js');
        $this->view->setVars([
            'carInfo' => $carInfo,
            'check'   => $check,
        ]);
    }

    /**
     * 获取车辆信息
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/9
     */
    public function getCarAction()
    {
        UserPower::checkUserPower('Lm_Car_CarList') or die('缺少权限');
        try {
            $sql  = "select iUCId,iCarId,tStartTime,tRealStart,tRealEnd,tEndTime,iState  from  XHLm_UseCar WHERE iState = 3 AND tRealEnd is NULL  order by tStartTime ";
            $sql  = "select c.* from ({$sql}) as c group by c.iCarId";
            $sql  = "select c.iCarId,c.sCarName,c.sPlateNum,c.iPersonNum,c.bDelete,uc.iUCId,uc.tStartTime,uc.tRealStart,uc.tEndTime,uc.tRealEnd,uc.iState,c.iCreateUserId,c.tLastModifyDate,c.iLastModifyUserId from  XHLm_Car  as c 
                    LEFT JOIN ($sql) as uc ON uc.iCarId = c.iCarId WHERE c.bDelete = 0";
            $data = Main::runSqlPage(['query' => "select :columns: from ({$sql}) as t", 'columns' => 't.*']);
            foreach ($data['rows'] as $index => $row) {
                $data['rows'][$index]['useStatus'] = $row['tRealStart'] == null ? '未使用' : '使用中';
            }
            Main::runUserNameById($data['rows'], [
                'iCreateUserId'     => 'iCreateUserId',
                'iLastModifyUserId' => 'iLastModifyUserId'
            ], true);

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * 确认
     *
     * create by dale 2017/12/28
     */
    public function confirmAction($iUCId, $flag)
    {
        if (!$iUCId) {
            die('缺少参数');
        }
        $this->view->pick('car/confirm');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::datetimePicker();
        Assets::importJs('js/car/confirm.js');
        $carInfo = XHLmUseCar::findFirst($iUCId)->toArray();
        if ($carInfo['iState'] != 3) {
            return $this->sendViewError('没有审批通过');
        }
        $this->view->setVars([
            'flag'    => $flag,
            'iUCId'   => $iUCId,
            'carInfo' => json_encode($carInfo),
            'time'    => date('Y-m-d H:i', time())
        ]);
    }

    /**
     * 车辆使用/归还
     *
     * @param $flag  true 还车  flase 用车
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     */
    public function saveConfirmAction($flag = null)
    {
        if (!UserPower::checkUserPower('Lm_Car_CarList_Confirm')) {
            return $this->sendErrorResponse(400, '缺少权限');
        }
        $mDesc       = $this->request->getPost('mDesc', 'string');
        $iUCId       = $this->request->getPost('iUCId', 'int');
        $time        = $this->request->getPost('time', 'string');
        $sDriverName = $this->request->getPost('sDriverName', 'string');
//        var_dump($sDriverName);die;
        $iCarId = $this->request->getPost('iCarId', 'string');
        if (!$iUCId || !$time) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XHLmUseCar::findFirst($iUCId);
        if ($obj->iState != 3) {
            return $this->sendErrorResponse(400, '尚未审批通过');
        }
        if ($sDriverName) {
            $obj->sDriverName = $sDriverName;
        }
        if ($iCarId) {
            $obj->iCarId = $iCarId;
        }
        if (!isset($flag)) {
            $obj->tRealStart = $time;
        } else {
            $obj->tRealEnd = $time;
        }
        $mDesc      = (isset($flag) ? '还车：' : '用车：') . $mDesc . '&#10';
        $obj->mDesc .= $mDesc;
        if (!$obj->save()) {
            return $this->sendErrorResponse(500, '保存失败');
        }

        return $this->sendSuccessResponse('保存成功');
    }


    /**
     * 保存、编辑车辆
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171009
     */
    public function saveCarAction()
    {
        $id = $this->request->getPost('iCarId', 'string');
        if ($id != "") {
            UserPower::checkUserPower('Lm_Car_CarList_Edit') or die('缺少权限');
            $obj = XHLmCar::findFirst([
                'conditions' => 'bDelete=0 AND iCarId=:iCarId:',
                'bind'       => ['iCarId' => $id]
            ]);
        } else {
            UserPower::checkUserPower('Lm_Car_CarList_Add') or die('缺少权限');
            $obj = new XHLmCar();
        }
        $obj->assign($this->request->getPost());
        $check = $this->checkPlateNum($this->request->getPost('sPlateNum', 'string'), $id);
        if ($check) {
            return $this->sendErrorResponse(500, '该车辆已存在,请不要重复创建');
        }
        if ($obj->save()) {
            if ($id) {
                return $this->sendSuccessResponse('编辑车辆成功');
            } else {
                return $this->sendSuccessResponse('新增车辆成功');
            }
        } else {
            if ($id) {
                return $this->sendSuccessResponse(500, '编辑车辆失败');
            } else {
                return $this->sendErrorResponse(500, '新增车辆失败');
            }
        }
    }

    /**
     * 删除车辆
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/9
     */
    public function delCarAction()
    {
        UserPower::checkUserPower('Lm_Car_CarList_Del') or die('缺少权限');
        $ids = $this->request->getPost('ids', 'string') or die('缺少参数');
        $userId = Main::getLoginUserInfo('userId');
        $ids    = explode(',', $ids);
        if (Main::getLoginUserInfo('logonName') != 'admin') {
            $cars = XHLmCar::find([
                'conditions' => 'bDelete=0 AND iCarId in ({ids:array}) AND iCreateUserId = :iCreateUserId:',
                'bind'       => ['ids' => $ids, 'iCreateUserId' => $userId]
            ]);
        } else {
            $cars = XHLmCar::find([
                'conditions' => 'bDelete=0 AND iCarId in ({ids:array})',
                'bind'       => ['ids' => $ids]
            ]);
        }

        foreach ($cars as $car) {
            $car->bDelete = 1;
            if (!$car->save()) {
                return $this->sendErrorResponse(500, '车辆删除失败');
            }
        }

        return $this->sendSuccessResponse('车辆删除成功,已过滤无法删除的');
    }

    /**
     * 验证车牌号
     *
     * @param $sPlateNum
     * @param null $id
     *
     * @return bool
     * created by dale 2017/10/9
     */
    public function checkPlateNum($sPlateNum, $id = null)
    {
        if ($id) {
            $car = XHLmCar::findFirst([
                'conditions' => 'bDelete=0 AND sPlateNum=:sPlateNum: AND iCarId!=:iCarId:',
                'bind'       => ['sPlateNum' => $sPlateNum, 'iCarId' => $id]
            ]);
        } else {
            $car = XHLmCar::findFirst([
                'conditions' => 'bDelete=0 AND sPlateNum=:sPlateNum:',
                'bind'       => ['sPlateNum' => $sPlateNum]
            ]);
        }
        if ($car) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 用车列表
     *
     * @param  $read
     * created by dale 2017/10/10
     */
    public function useCarListAction($read = null)
    {
        $stateType = $this->request->getQuery('stateType');
        UserPower::checkUserPower('Lm_Car_UseCarList') or die('缺少权限');
        Assets::easyUI();
        Assets::sweetAlert2();
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        if (!isset($read)) {
            Assets::importJs('js/car/useCarList.js');
        } else {
            Assets::importMainJs('assets/xh/xhTop.js');
            Assets::importJs('js/car/carReadList.js');
        }
        $this->view->pick('car/useCarList');
        Template::exists('useCarList', 'list') or die(Main::showMessageModal('useCarList 配置文件不存在，请先创建！', 109106002));
        if (!$read) {
            $listButtonArr = $listSearchArr = [];
            if ($stateType == 1) {
                if (UserPower::checkUserPower('Lm_Car_UseCarList_Add')) {
                    $listButtonArr[] = array(
                        'plain' => 'true',
                        'id'    => 'bt_list_add',
                        'text'  => '申请公车',
                        'icon'  => 'fa-plus'
                    );
                }
                if (UserPower::checkUserPower('Lm_Car_UseCarList_Add')) {
                    $listButtonArr[] = array(
                        'plain' => 'true',
                        'id'    => 'bt_list_usePrivate',
                        'text'  => '申请私车',
                        'icon'  => 'fa-plus'
                    );
                }
            }
            if ($stateType != 3 && $stateType != 4) {
                if (UserPower::checkUserPower('Lm_Car_UseCarList_Del')) {
                    $listButtonArr[] = array(
                        'plain' => 'true',
                        'id'    => 'bt_list_del',
                        'text'  => '删除申请',
                        'icon'  => 'fa-trash'
                    );
                }
            }
            if ($stateType != 1 && $stateType != 4) {
                $listButtonArr[] = array(
                    'plain' => 'true',
                    'id'    => 'bt_list_undo',
                    'text'  => '撤销申请',
                    'icon'  => 'fa-undo'
                );
            }
            if ($stateType == 2 || $stateType == 3 || $stateType == 4) {
                $listButtonArr[] = array(
                    'plain' => 'true',
                    'id'    => 'bt_list_Desc',
                    'text'  => '查看审批意见',
                    'icon'  => 'fa-eye'
                );
            }
            if (in_array($stateType, [2, 3])) {
                $carType         = ['' => '--全部--', 1 => '公车', 2 => '私车'];
                $listSearchArr[] = array(
                    'type'    => 'select',
                    'id'      => 'list_carType',
                    'data'    => $carType,
                    'default' => ''
                );
            }
            if ($stateType == 3) {
                $carState        = ['' => '--全部--', 1 => '未开始', 2 => '已开始', 3 => '已结束'];
                $listSearchArr[] = array(
                    'type'    => 'select',
                    'id'      => 'list_carState',
                    'data'    => $carState,
                    'default' => ''
                );
            }
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr[] = array(
                'type'  => 'button',
                'id'    => 'bt_list_search',
                'text'  => '查找',
                'icon'  => 'fa-search',
                'style' => 'margin-left:10px'
            );

            $filed = [
                'iUCId',
                'iDepId',
                'iCarId',
                'carIcon',
                'sApplyName',
                'sDepName',
                'sDriverName',
                'sCarName',
                'sPlateNum',
                'sCountry',
                'tStartTime',
                'tEndTime',
                'tRealStart',
                'tRealEnd',
                'iCUId',
                'iState',
                'tLastModifyDate',
                'iLastModifyUserId'
            ];
            $this->view->setVars(array(
                'useCarList' => Template::createList('useCarList', 'useCarList', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                    'field'         => $filed,
                ]),
            ));
        } else {
            $listButton = [];
            if (UserPower::checkUserPower('Lm_Car_CarList_Confirm')) {
                $listButton[] = array(
                    'plain' => 'true',
                    'id'    => 'bt_list_startUse',
                    'text'  => '取车确认',
                    'icon'  => 'fa fa-key'
                );
                $listButton[] = array(
                    'plain' => 'true',
                    'id'    => 'bt_list_endUse',
                    'text'  => '还车确认',
                    'icon'  => 'fa fa-key'
                );
            }
            $this->view->setVars(array(
                'useCarList' => Template::createList('useCarList', 'useCarList', [
                    'field'         => array(
                        'iUCId',
                        'passIcon',
                        'sApplyName',
                        'sDepName',
                        'sDriverName',
                        'sCarName',
                        'mReason',
                        'mDestination',
                        'tStartTime',
                        'tEndTime',
                        'tRealStart',
                        'tRealEnd',
                        'iState'
                    ),
                    'buttonToolbar' => Template::createButtonToolBar($listButton),
                ]),
            ));
        }
    }

    /**
     * 用车表单
     *
     * created by dale 2017/10/10
     */
    public function useCarFormAction()
    {

        $id = $this->request->getQuery('iUCId', 'string');

        if (isset($id)) {
            UserPower::checkUserPower('Lm_Car_UseCarList_Edit')
            or die('缺少权限<script>window.onload = function(){ $(\'#bt_form_add\').hide(); };</script>');
        } else {
            UserPower::checkUserPower('Lm_Car_UseCarList_Add')
            or die('缺少权限<script>window.onload = function(){ $(\'#bt_form_add\').hide(); };</script>');
        }
        $this->view->pick('car/useCarForm');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/car/useCarForm.js');
        Assets::select2();
        Assets::datetimePicker();
        Assets::easyUI();
        $custInfo = XhcustInfo::find([
            'columns'    => 'iSchoolId,iCUId,sSchoolName',
            'conditions' => 'bDelete = 0'
        ])->toArray();
        $custInfo = array_column($custInfo, 'sSchoolName', 'iCUId');
        $userId   = Main::getLoginUserInfo('userId');
        if (isset($id)) {
            $car             = XHLmUseCar::findFirst([
                'conditions' => 'bDelete=0 AND iUCId=:iUCId:',
                'bind'       => ['iUCId' => $id],
            ])->toArray();
            $car['sDepName'] = XhhrmDepart::getDepEnum()[$car['iDepId']];
            if ($car['iState'] == 0 && $car['iCreateUserId'] == $userId) {
                $car['iState'] = 1;
                $checkStr      = '';
            } elseif ($car['iState'] == 1 && $car['iChargeId'] == $userId) { //部门审批阶段
                $chargeArr = $this->getChargeById($car['iCreateUserId'], true);
                if (end($chargeArr) == $userId) {
                    $car['iState'] = 2;
                    $checkStr      = '';
                }
            } elseif ($car['iState'] == 2) {
                $flag = !is_bool(
                    strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId))
                );
                if ($flag) {
                    $car['iState'] = 3;
                    $checkStr      = '';
                } else {
                    $checkStr = "window.onload = function(){ $('#bt_form_add').hide(); };";
                }

            } else {
                $checkStr = "window.onload = function(){ $('#bt_form_add').hide(); };";
            }
            $carInfo = json_encode($car);
        } else {
            $carInfo  = '1';
            $checkStr = "";
        }
        $staff = XhhrmStaff::findFirst([
            'conditions' => 'bDelete=0 AND iUserId=:iUserId:',
            'bind'       => ['iUserId' => $userId],
        ]);
        if ($staff) {
            $staff    = $staff->toArray();
            $iPDepId  = end(array_filter(explode(',', $staff['sDepIds'])));
            $sDepName = XhhrmDepart::getDepEnum()[$iPDepId];
        } else {
            $checkStr            = "window.onload = function(){ $('#bt_form_add').hide(); };";
            $staff['sStaffName'] = '账号未绑定';
            $iPDepId             = '';
            $sDepName            = '';
        }
        $flag   = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId)));
        $fixBtn = null;
        if ($flag) {
            $fixBtn = '<a id="bt_form_fixData" class="btn-load" style="display: none">保存</a>';
        }
        $leavers = $this->getDepStaffAction(true);
        $drivers = $this->carDriverAction()->getContent();
//        var_dump($drivers);die;
        $this->view->setVars([
            'carInfo'  => $carInfo,
            'userName' => $staff['sStaffName'],
            'iDepId'   => $iPDepId,
            'sDepName' => $sDepName,
            'check'    => $checkStr,
            'cars'     => XHLmCar::getCarEnum(),
            'custInfo' => $custInfo,
            'fixBtn'   => $fixBtn,
            'leavers'  => json_encode($leavers),
            'drivers'  => $drivers
        ]);
    }


    public function getUseCarAction($read = null)
    {
        UserPower::checkUserPower('Lm_Car_UseCarList') or die('缺少权限');
        $key       = $this->request->getPost('key', 'string');
        $carType   = $this->request->getPost('carType', 'string');
        $stateType = $this->request->getQuery('stateType', 'int');
        $carState  = $this->request->getPost('carState', 'string');
        $order     = $this->request->getPost('order', 'string');
        $sort      = $this->request->getPost('sort', 'string');
        $builder   = $this->modelsManager->createBuilder()
                                         ->columns('uc.iUCId,uc.iDepId,uc.iCarId,sApplyName,sDriverName,uc.iChargeId,uc.sCarType,uc.sCountry,uc.iCUId,
                       tStartTime,tEndTime,mReason,mDestination,mOfficeIdea,uc.iState,uc.tRealStart,uc.tRealEnd,
                       c.sCarName,c.sPlateNum,c.iPersonNum,d.sDepName,uc.tCreateDate,uc.sCarOwner,uc.sCarPlate,
                       uc.iCreateUserId,uc.tLastModifyDate,uc.iLastModifyUserId')
            ->from(['uc'=>'Admin\Models\lm\XHLmUseCar'])
            ->where('uc.bDelete=0')
            ->leftJoin('Admin\Models\lm\XHLmCar', 'uc.iCarId=c.iCarId', 'c')
            ->leftJoin('Admin\Models\hrm\XhhrmDepart','uc.iDepId=d.iDepId','d');
        if ($stateType) {
            switch ($stateType) {
                case 1:
                    $builder->andWhere('uc.iState = 0 OR uc.iState = 4 ');
                    break;
                case 2:
                    $builder->andWhere('uc.iState = 1 OR uc.iState = 2 ');
                    break;
                case 3:
                    $builder->andWhere('uc.iState = 3 ');
                    break;
                case 4:
                    $builder->andWhere('uc.iState = 4 ');
                    break;
            }
        }
        if ($carState) { //$carState = [''=>'--全部--',1=>'未开始',2=>'已开始',3=>'已结束'];
            switch ($carState) {
                case 1:
                    $builder->andWhere('uc.tRealStart is null ');
                    break;
                case 2:
                    $builder->andWhere('uc.tRealStart is not null  AND  uc.tRealEnd  is null ');
                    break;
                case 3:
                    $builder->andWhere('uc.tRealEnd is not null ');
                    break;
            }
        }
        if ($order && $sort) {
            if ($sort == 'sPlateNum') {
                $builder->orderBy('c.' . $sort . ' ' . $order . ' ');
            } else {
                $builder->orderBy('uc.' . $sort . ' ' . $order . ' ');
            }

        } else {
            $builder->orderBy('uc.tStartTime desc');
        }

        if (!$read) {
            $userId = Main::getLoginUserInfo('userId');
            $flag   = !is_bool(
                strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId))
            );
            if (!UserPower::checkUserPower('Lm_Car_UseCarList_All')) {
//            if($flag){  //如果找的到,状态为2,或者自己创建的
//                $builder->andWhere('uc.iCreateUserId=:iUserId:',array('iUserId'=>$userId));
//            }else{  //如果找不到,自己创建的或者负责人是他

                if (!$flag) {
                    $builder->andWhere('uc.iCreateUserId=:iUserId: OR uc.iChargeId=:userId: OR FIND_IN_SET(:iUserId:,uc.sChargList) ', array(
                        'iUserId' => '' . $userId . '',
                        'userId'  => $userId
                    ));
                } else {
                    $builder->andWhere('uc.iCreateUserId=:iUserId: OR uc.iChargeId=:iUserId: OR uc.iState >= 2 OR FIND_IN_SET(:userId:,uc.sChargList) ', array(
                        'iUserId' => $userId,
                        'userId'  => '' . $userId . ''
                    ));
                }

            }
            if ($key) {
                $builder->andWhere('uc.sApplyName like :key: or uc.sDriverName like :key:', array('key' => '%' . $key . '%'));
            }

            if ($carType) {
                if ($carType == 1) {
                    $builder->andWhere('uc.iCarId is not null');
                } elseif ($carType == 2) {
                    $builder->andWhere('uc.iCarId is null');
                }
            }
        } else {
            $iCarId = $this->request->getPost('iCarId') or die('缺少参数');
            $builder->andWhere('uc.iState != 4 AND uc.tRealEnd is null ')->andWhere('uc.iCarId =:iCarId:', ['iCarId' => $iCarId]);
            $builder->orderBy('uc.tStartTime desc');
        }
        $data  = Main::runBuilderPaginator($builder, true);
        $enums = self::$enums;

        $custInfo = XhcustInfo::find([
            'columns'    => 'iSchoolId,iCUId,sSchoolName',
            'conditions' => 'bDelete = 0'
        ])->toArray();
        $custInfo = array_column($custInfo, 'sSchoolName', 'iCUId');
        foreach ($data['rows'] as $index => $row) {
            if ($data['rows'][$index]['iState'] == 4) {
                $data['rows'][$index]['carIcon'] = '<i class="fa fa-bus" style="color:grey;" ></i>';
                if ($row['iCarId'] == null) {
                    $data['rows'][$index]['carIcon'] = '<i class="fa fa-car" style="color:grey;" ></i>';
                }
            } else {
                $data['rows'][$index]['carIcon'] = '<i class="fa fa-bus" style="color:blue;" ></i>';
                if ($row['iCarId'] == null) {
                    $data['rows'][$index]['carIcon'] = '<i class="fa fa-car" style="color:green;" ></i>';
                }
            }
            if ($data['rows'][$index]['iState'] == 3) {
                $data['rows'][$index]['passIcon'] = '<i class="fa fa-check" style="color:#2baab1;" ></i>';
            }
            if ($data['rows'][$index]['iState'] == 1) {
                $data['rows'][$index]['iState'] = $enums['iState'][$row['iState']];
                if (isset($data['rows'][$index]['iChargeId'])) {
                    $chargeId                       = $data['rows'][$index]['iChargeId'];
                    $name                           = XhhrmStaff::getStaffNameById([$chargeId])[$chargeId];
                    $data['rows'][$index]['iState'] = '<div title="' . $name . '">' .
                                                      $data['rows'][$index]['iState'] . '</div>';
                }
            } else {
                $data['rows'][$index]['iState'] = $enums['iState'][$row['iState']];
            }
            $data['rows'][$index]['iCUId'] = isset($custInfo[$row['iCUId']]) ? $custInfo[$row['iCUId']] : '';

            if ($row['iCarId'] == null) {
                $data['rows'][$index]['sCarName']  = $row['sCarType'];
                $data['rows'][$index]['sPlateNum'] = $row['sCarPlate'];
            }
        }
        Main::runUserNameById($data['rows'], ['iLastModifyUserId' => 'iLastModifyUserId'], true);

        return $this->sendJsonResponse($data);
    }


    /**
     * 保存申请
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017/10/10
     */
    public function saveUseCarAction()
    {
        $id = $this->request->getPost('iUCId', 'string');
//        $sDriverName = $this->request->getPost('sDriverName','string');
        $sTravellers = $this->request->getPost('sTravellers');
        $iCarId      = $this->request->getPost('iCarId', 'int');
        $sDriverName = $this->request->getPost('sDriverName', 'string');
        $sCarOwner   = $this->request->getPost('sCarOwner', 'string');
        $sCarPlate   = $this->request->getPost('sCarPlate', 'string');
        $sCarType    = $this->request->getPost('sCarType', 'string');
        $postData = $this->request->getPost();
        if (!$sTravellers) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        if (!$iCarId && (!$sCarOwner || !$sCarPlate || !$sCarType)) {
            return $this->sendErrorResponse(400, '缺少私家车信息');
        }
        if (!$sCarOwner && (!$iCarId || !$sDriverName)) {
            return $this->sendErrorResponse(400, '缺少公车信息');
        }
        if (!$postData['sProvince'] || !$postData['sCity'] || !$postData['sCountry']) {
            return $this->sendErrorResponse(400, '请完整填写学校区域信息');
        }
        if (!$postData['mDestination']) {
            return $this->sendErrorResponse(400, '请填写详细地址');
        }
        if (!$postData['mReason']) {
            return $this->sendErrorResponse(400, '请填写申请事由');
        }
        if (!$postData['tStartTime'] || !$postData['tEndTime']) {
            return $this->sendErrorResponse(400, '请完整填写开始结束时间');
        }
        try {
            if ($id != "") {
                UserPower::checkUserPower('Lm_Car_UseCarList_Edit') or die('缺少权限');
                $obj = XHLmUseCar::findFirst([
                    'conditions' => 'bDelete=0 AND iUCId=:iUCId:',
                    'bind'       => ['iUCId' => $id]
                ]);
            } else {
                UserPower::checkUserPower('Lm_Car_UseCarList_Add') or die('缺少权限');
                $obj = new XHLmUseCar();
            }
            $obj->assign($this->request->getPost());
            $obj->sTravellers = implode(',', $sTravellers);
            $userId           = $obj->iCreateUserId ? : Main::getLoginUserInfo('userId');
            $chargeArr        = $this->getChargeById($userId, true);

            if (!$id) { //第一次进来
                $obj->iChargeId  = isset($chargeArr[0]) ? $chargeArr[0] : null;
                $obj->sChargList = '';
                if ($obj->iCarId != null) {
                    $check = $this->checkTime($obj->tStartTime, $obj->tEndTime, $obj->iCarId);
                    if ($check) {
                        return $this->sendErrorResponse(500, '当前时间段已经占用');
                    }
                }
                if ($obj->iChargeId == null) {
                    $obj->iState = 2;
                }
            } else {
                $mDepText = $this->request->getPost('mDepText', 'string');
                if ($mDepText != null) {
                    $obj = $this->saveDesc($obj, $mDepText);
                }
//                if($obj->mDescJson == null && $mDepText != null){
//                    $arr = [];
//                    $arr[] = ['userId'=>Main::getLoginUserInfo('userId'),'text'=>$mDepText,'time'=>date('Y-m-d H:i',time())];
//                    $obj->mDescJson = json_encode($arr);
//                }else if($obj->mDescJson != null && $mDepText != null ){
//                    $arr   = json_decode($obj->mDescJson,true);
//                    $arr[] = ['userId'=>Main::getLoginUserInfo('userId'),'text'=>$mDepText,'time'=>date('Y-m-d H:i',time())];
//                    $obj->mDescJson = json_encode($arr);
//                }
                if ($obj->iState == 1) {
                    if ($obj->iChargeId == Main::getLoginUserInfo('userId')) {
                        if ($obj->sChargList == '' && $obj->iChargeId != end($chargeArr)) { //部门第一次审核
                            $obj->iChargeId  = $chargeArr[1];
                            $obj->sChargList = $chargeArr[0] . ',';
                        } else {
                            foreach ($chargeArr as $index => $value) {
                                if ($value == $obj->iChargeId) {
                                    if ($chargeArr[$index + 1] == $obj->iChargeId) {
                                        continue;
                                    }
                                    $obj->iChargeId  = $chargeArr[$index + 1];
                                    $obj->sChargList .= $chargeArr[$index] . ',';
                                    break;
                                }
                            }

                        }
                    }
                } elseif ($obj->iState == 2) { //最后一个
                    $obj->sChargList .= $obj->iChargeId . ',';
                } elseif ($obj->iState == 3) { //当前登录的办公室负责人
                    $userId          = Main::getLoginUserInfo('userId');
                    $obj->sChargList .= $userId;
                }
            }
            if ($obj->save()) {
                if ($obj->iState == 1) {
                    $staff = XhhrmStaff::findFirst([
                        'columns'    => 'sSelfPhone',
                        'conditions' => 'bDelete = 0 AND iUserId = :iUserId:',
                        'bind'       => ['iUserId' => $obj->iChargeId],
                    ]);
                    if (!$staff) {
                        return $this->sendErrorResponse(500, '找不到人力表中对应账号');
                    }
                    if (!$this->sendMsgToPhone($staff->sSelfPhone, '您有一条车辆申请需要审批')) {
                        return $this->sendErrorResponse(500, '短信发送失败');
                    } else {
                        return $this->sendSuccessResponse($staff->sSelfPhone . '短信发送成功');
                    }
                } elseif ($obj->iState == 2) {
                    $ids    = $this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']);
                    $ids    = array_values(array_filter(explode(',', $ids)));
                    $staffs = XhhrmStaff::find([
                        'columns'    => 'sSelfPhone',
                        'conditions' => 'bDelete = 0 AND iUserId in ({ids:array})',
                        'bind'       => ['ids' => $ids],
                    ])->toArray();
                    if (count($staffs) <= 0) {
                        return $this->sendErrorResponse(500, '找不到人力表中对应账号');
                    }
                    foreach ($staffs as $staff) {
                        if (!$this->sendMsgToPhone($staff['sSelfPhone'], '您有一条车辆申请需要审批')) {
                            return $this->sendErrorResponse(500, '短信发送失败');
                        }
                    }

                    return $this->sendSuccessResponse(json_encode($staffs) . '短信发送成功');
                } elseif ($obj->iState == 3) {
                    $staff = XhhrmStaff::findFirst([
                        'columns'    => 'sSelfPhone',
                        'conditions' => 'bDelete = 0 AND iUserId = :iUserId:',
                        'bind'       => ['iUserId' => $obj->iCreateUserId],
                    ]);
                    if (!$staff) {
                        return $this->sendErrorResponse(500, '找不到人力表中对应账号');
                    }
                    if (!$this->sendMsgToPhone($staff->sSelfPhone, '您的车辆申请已经审批通过')) {
                        return $this->sendErrorResponse(500, '短信发送失败');
                    } else {
                        return $this->sendSuccessResponse($staff->sSelfPhone . '短信发送成功');
                    }
                }

                return $this->sendSuccessResponse('发起申请用车成功');
            } else {
                if ($id) {
                    return $this->sendSuccessResponse(500, '发起申请用车失败');
                } else {
                    return $this->sendErrorResponse(500, '发起申请用车失败');
                }
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 手机端处理审批
     *
     * create by dale 2018/1/11
     */
    public function saveCarStateAction()
    {
        $id = $this->request->getPost('iUCId', 'string');
        try {
            $obj       = XHLmUseCar::findFirst([
                'conditions' => 'bDelete=0 AND iUCId=:iUCId:',
                'bind'       => ['iUCId' => $id]
            ]);
            $userId    = $obj->iCreateUserId;
            $chargeArr = $this->getChargeById($userId, true);
            $obj->assign($this->request->getPost());
            //审批备注处理
            $mDepText = $this->request->getPost('mDepText', 'string');
//            if($obj->mDescJson == null && $mDepText != null){
//                $arr = [];
//                $arr[] = ['userId'=>Main::getLoginUserInfo('userId'),'text'=>$mDepText,'time'=>date('Y-m-d H:i',time())];
//                $obj->mDescJson = json_encode($arr);
//            }else if($obj->mDescJson != null && $mDepText != null ){
//                $arr   = json_decode($obj->mDescJson,true);
//                $arr[] = ['userId'=>Main::getLoginUserInfo('userId'),'text'=>$mDepText,'time'=>date('Y-m-d H:i',time())];
//                $obj->mDescJson = json_encode($arr);
//            }
            if ($mDepText != null) {
                $obj = $this->saveDesc($obj, $mDepText);
            }

            if ($obj->iState == 1) {
                if ($obj->iChargeId == Main::getLoginUserInfo('userId')) {
                    if ($obj->sChargList == '' && $obj->iChargeId != end($chargeArr)) { //部门第一次审核
                        $obj->iChargeId  = $chargeArr[1];
                        $obj->sChargList = $chargeArr[0] . ',';
                    } else {
                        foreach ($chargeArr as $index => $value) {
                            if ($value == $obj->iChargeId) {
                                $obj->iChargeId  = $chargeArr[$index + 1];
                                $obj->sChargList .= $chargeArr[$index] . ',';
                                break;
                            }
                        }
                    }
                }
            } elseif ($obj->iState == 2) { //最后一个
                $obj->sChargList .= $obj->iChargeId . ',';
            } elseif ($obj->iState == 3) { //当前登录的办公室负责人
                $userId = Main::getLoginUserInfo('userId');
                $obj->sChargList .= $userId;
            }

            if ($obj->save()) {
                if ($obj->iState == 1) {
                    $staff = XhhrmStaff::findFirst([
                        'columns'    => 'sSelfPhone',
                        'conditions' => 'bDelete = 0 AND iUserId = :iUserId:',
                        'bind'       => ['iUserId' => $obj->iChargeId],
                    ]);
                    if (!$staff) {
                        return $this->sendErrorResponse(500, '找不到人力表中对应账号');
                    }
                    if (!$this->sendMsgToPhone($staff->sSelfPhone, '您有一条车辆申请需要审批')) {
                        return $this->sendErrorResponse(500, '短信发送失败');
                    } else {
                        return $this->sendSuccessResponse($staff->sSelfPhone . '短信发送成功');
                    }
                } elseif ($obj->iState == 2) {
                    $ids = $this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']);
                    $ids = array_values(array_filter(explode(',', $ids)));
//                    var_dump($ids);die;
                    $staffs = XhhrmStaff::find([
                        'columns'    => 'sSelfPhone',
                        'conditions' => 'bDelete = 0 AND iUserId in ({ids:array})',
                        'bind'       => ['ids' => $ids],
                    ])->toArray();
                    if (count($staffs) <= 0) {
                        return $this->sendErrorResponse(500, '找不到人力表中对应账号');
                    }
                    foreach ($staffs as $staff) {
                        if (!$this->sendMsgToPhone($staff['sSelfPhone'], '您有一条车辆申请需要审批')) {
                            return $this->sendErrorResponse(500, '短信发送失败');
                        }
                    }

                    return $this->sendSuccessResponse(json_encode($staffs) . '短信发送成功');
                } elseif ($obj->iState == 3) {
                    $staff = XhhrmStaff::findFirst([
                        'columns'    => 'sSelfPhone',
                        'conditions' => 'bDelete = 0 AND iUserId = :iUserId:',
                        'bind'       => ['iUserId' => $obj->iCreateUserId],
                    ]);
                    if (!$staff) {
                        return $this->sendErrorResponse(500, '找不到人力表中对应账号');
                    }
                    if (!$this->sendMsgToPhone($staff->sSelfPhone, '您的车辆申请已经审批通过')) {
                        return $this->sendErrorResponse(500, '短信发送失败');
                    } else {
                        return $this->sendSuccessResponse($staff->sSelfPhone . '短信发送成功');
                    }
                }

                return $this->sendSuccessResponse('发起申请用车成功');
            } else {
                if ($id) {
                    return $this->sendSuccessResponse(500, '发起申请用车失败');
                } else {
                    return $this->sendErrorResponse(500, '发起申请用车失败');
                }
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 保存审批意见
     *
     * @param $obj
     * @param $mDepText
     *
     * @return mixed
     * create by dale 20180367
     */
    public function saveDesc($obj, $mDepText)
    {
        if ($obj->mDescJson == null) {
            $arr            = [];
            $arr[]          = [
                'userId' => Main::getLoginUserInfo('userId'),
                'text'   => $mDepText,
                'time'   => date('Y-m-d H:i', time())
            ];
            $obj->mDescJson = json_encode($arr);
        } elseif ($obj->mDescJson != null) {
            $arr            = json_decode($obj->mDescJson, true);
            $arr[]          = [
                'userId' => Main::getLoginUserInfo('userId'),
                'text'   => $mDepText,
                'time'   => date('Y-m-d H:i', time())
            ];
            $obj->mDescJson = json_encode($arr);
        }

        return $obj;
    }


    /**
     * 查看时间段是否占用
     *
     * @param $startTime
     * @param $endTime
     * @param $carId
     *
     * @return bool
     * create by dale 2018/1/9
     */
    public function checkTime($startTime, $endTime, $carId)
    {
        $sql  = "select tEndTime,iCarId from XHLm_UseCar WHERE bDelete = 0 AND ((tStartTime <= '{$startTime}' AND tEndTime >= '{$endTime}') OR (tStartTime >= '{$startTime}' AND tStartTime <= '{$endTime}') OR (tEndTime >= '{$startTime}' AND tEndTime <= '{$endTime}')  ) AND iState != 4 and tRealEnd is null  AND iCarId ={$carId} ";
        $data = $this->db->fetchAll($sql);
        if (count($data) > 0) {
            return true;
        }

        return false;
    }


    /**
     * 发送短信
     *
     * @param $phoneNum
     * @param $msg
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale 20180109
     * modify by ck 20180629
     */
    public function sendMsgToPhone($phoneNum, $msg)
    {
        return Main::sendSMS($phoneNum, $msg);
    }

    /*
     * 将指定id人查看其所有部门负责人 由上级层层上推
     *
     * @param $userId
     * @param bool $isArr
     * @return array|string
     *
     * create by dale 20180108
     * modify by dale 20190125 去除相邻的重复上级
     */
    public function getChargeById($userId, $isArr = false)
    {
        $staff  = XhhrmStaff::findFirst([
            'columns'    => 'iUserId,sDepIds',
            'conditions' => 'bDelete = 0 AND  iUserId = :iUserId: and iStaffStatus = 1',
            'bind'       => ['iUserId' => $userId]
        ]);
        $arr    = [];
        $depIds = array_filter(explode(',', $staff->sDepIds));
        if (count($depIds) > 0) {
            foreach ($depIds as $depId) {
                $sql = "select iUserId from XHHrm_Staff  WHERE find_in_set('" . $depId . "',sChargeDeps) and bDelete = 0";
                $chargeId = $this->db->fetchOne($sql);
                if (isset($chargeId['iUserId'])) {  //没有直接走上级的上级
                    $arr[] = $chargeId['iUserId'];
                }
            }
            if ($arr[0] == $userId) {
                unset($arr[0]);
            }
            $arr = array_values($arr);
            $newArr = [];
            foreach ($arr as $index => $val) {  //去除相邻重复userId
                if ($index == 0) {
                    $newArr[] = $val;
                    continue;
                }
                if ($val == end($newArr)) {
                    continue;
                } else {
                    $newArr[] = $val;
                }
            }
            if ($isArr) {
                return $newArr;
            }
            return implode(',', $newArr);
        }
    }


    /**
     * 删除申请
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/10
     */
    public function delUseCarAction()
    {
        UserPower::checkUserPower('Lm_Car_UseCarList_Del') or die('缺少权限');
        $ids = $this->request->getPost('ids', 'string') or die('缺少参数');
        $ids    = explode(',', $ids);
        $cars   = XHLmUseCar::find([
            'conditions' => 'bDelete=0 AND iUCId in ({ids:array})',
            'bind'       => ['ids' => $ids]
        ]);
        $userId = Main::getLoginUserInfo('userId');
        $flag   = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId)));
        foreach ($cars as $car) {
            $car->bDelete = 1;
            if (($car->iState != 3 && $car->iCreateUserId == $userId) ||
                Main::getLoginUserInfo("logonName") == 'admin') {
                if (!$car->save()) {
                    return $this->sendErrorResponse(500, '车辆申请记录删除失败');
                }
            } else {
                if ($car->iState == 3) {
                    return $this->sendErrorResponse(500, '已经审批通过');
                } else {
                    return $this->sendErrorResponse(500, '没有权限');
                }
            }
        }

        return $this->sendSuccessResponse('车辆申请记录删除成功');
    }

    /**
     * 撤销申请
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/16
     */
    public function undoUseCarAction()
    {

        $id = $this->request->getPost('id', 'string') or die('缺少参数');
        $car    = XHLmUseCar::findFirst([
            'conditions' => 'bDelete=0 AND iUCId = :id:',
            'bind'       => ['id' => $id]
        ]);
        $userId = Main::getLoginUserInfo('userId');
        $flag   = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId)));
        if ($flag || User::isAdmin() || $car->iCreateUserId == Main::getLoginUserInfo('userId')) {
            $car->iState = 4;
            $text        = $this->request->getPost('desc');
            if ($text != null) {
                $car = $this->saveDesc($car, $text);
            }
            if ($car->save()) {
                return $this->sendSuccessResponse('撤销成功');
            } else {
                return $this->sendErrorResponse(500, '撤销失败');
            }
        } else {
            return $this->sendErrorResponse(500, '仅限办公室负责人');
        }
    }


    /**
     * 获取顶层部门的人员信息
     * @param $isKey
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/10
     */
    public function getDepStaffAction($isKey = false)
    {
        $parameters = array(
            'columns'    => 'iDepId,sDepName',
            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: ",
            'bind'       => array('parentId' => 0, 'bDelete' => 0),
        );
        $objs       = XhhrmDepart::find($parameters)->toArray();
        $newArray   = [];
        foreach ($objs as $key => $obj) {
            $newArray[$key]['id']      = 'D-' . $obj['iDepId'];
            $newArray[$key]['text']    = $obj['sDepName'];
            $newArray[$key]['iconCls'] = 'fa fa-group';
            $staffs                    = XhhrmStaff::find([
                'conditions' => 'bDelete=0 AND sDepIds like :key:',
                'bind'       => ['key' => '%,' . $obj['iDepId'] . ',%'],
            ]);
            $staffs                    = $staffs->toArray();
            $staffArr                  = [];
            foreach ($staffs as $staff) {
                $item = [];
                if (!$isKey) {
                    $item['id'] = $staff['sStaffName'];
                } else {
                    $item['id'] = $staff['iUserId'];
                }
                $item['text']    = $staff['sStaffName'];
                $item['iconCls'] = 'fa fa-user';
                $staffArr[]      = $item;
            }
            $newArray[$key]['children'] = $staffArr;
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
        }
        if ($isKey) {
            return $newArray;
        }

        return $this->sendJsonResponse($newArray);
    }


    public function changeToId($str)
    {
//        $str='xjqdale,xjdale';
        $str   = explode(',', $str);
        $users = XhsysUser::find([
            'columns'    => 'iUserId',
            'conditions' => 'bDelete=0 AND sLogonName in ({ids:array})',
            'bind'       => ['ids' => $str]
        ])->toArray();

        $users = implode(',', array_column($users, 'iUserId'));

        return $users;
    }

    public function carEnumAction()
    {
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime   = $this->request->getPost('endTime', 'string');
        $carEnums  = XHLmCar::getCarEnum();
        $sql       = "select tEndTime,iCarId from XHLm_UseCar WHERE bDelete = 0 and IFNULL(tRealEnd, '') = '' AND ((tStartTime <= '{$startTime}' AND tEndTime >= '{$endTime}') OR (tStartTime >= '{$startTime}' AND tStartTime <= '{$endTime}') OR (tEndTime >= '{$startTime}' AND tEndTime <= '{$endTime}')  ) AND (iState != 4 and tRealEnd is null ) ";
        $data      = $this->db->fetchAll($sql);
        if (count($data) > 0) {
            foreach ($data as $index => $obj) {
                unset($carEnums[$obj['iCarId']]);
            }
        }

        return $this->sendJsonResponse($carEnums);
    }

    /**
     * 获取到这个时间段下面的可选司机
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180907
     */
    public function carDriverAction()
    {
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime   = $this->request->getPost('endTime', 'string');
        $staffArr  = XhhrmStaff::find([
            'columns'    => 'sStaffName as id,sStaffName as text',
            'conditions' => 'bDelete = 0 and iUserId is not null'
        ])->toArray();
//        $staff = array_column($staff, 'sStaffName', 'sStaffName');
        if ($startTime && $endTime) {
            $sql  = "select tEndTime,sDriverName from XHLm_UseCar WHERE bDelete = 0 and IFNULL(tRealEnd, '') = '' AND ((tStartTime <= '{$startTime}' AND tEndTime >= '{$endTime}') OR (tStartTime >= '{$startTime}' AND tStartTime <= '{$endTime}') OR (tEndTime >= '{$startTime}' AND tEndTime <= '{$endTime}')  ) AND iState != 4";
            $data = $this->db->fetchAll($sql);
            $data = array_column($data, 'sDriverName');
            if ($data) {
                foreach ($staffArr as $index => $staff) {
                    if (in_array($staff['id'], $data)) {
                        unset($staffArr[$index]);
                    }

                }
            }
        }

        return $this->sendJsonResponse($staffArr);
    }


    /**
     * 申请私家车
     *
     * create by dale 20180105
     */
    public function usePrivateAction()
    {
        $id = $this->request->getQuery('iUCId', 'string');

        if (isset($id)) {
            UserPower::checkUserPower('Lm_Car_UseCarList_Edit') or
            die('缺少权限<script>window.onload = function(){ $(\'#bt_form_add\').hide(); };</script>');
        } else {
            UserPower::checkUserPower('Lm_Car_UseCarList_Add') or
            die('缺少权限<script>window.onload = function(){ $(\'#bt_form_add\').hide(); };</script>');
        }
        $this->view->pick('car/usePrivate');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/car/usePrivate.js');
        Assets::datetimePicker();
        Assets::easyUI();
        Assets::select2();
        $userId = Main::getLoginUserInfo('userId');
        if (isset($id)) {
            $car             = XHLmUseCar::findFirst([
                'conditions' => 'bDelete=0 AND iUCId=:iUCId:',
                'bind'       => ['iUCId' => $id],
            ])->toArray();
            $car['sDepName'] = XhhrmDepart::getDepEnum()[$car['iDepId']];
            if ($car['iState'] == 0 && $car['iCreateUserId'] == $userId) {
                $car['iState'] = 1;
                $checkStr      = '';
            } elseif ($car['iState'] == 1 && $car['iChargeId'] == $userId) { //部门审批阶段
                $chargeArr = $this->getChargeById($car['iCreateUserId'], true);
                if (end($chargeArr) == $userId) {
                    $car['iState'] = 3;
                    $checkStr      = '';
                }
            } else {
                $checkStr = "window.onload = function(){ $('#bt_form_add').hide(); };";
            }
            $carInfo = json_encode($car);
        } else {
            $carInfo  = '1';
            $checkStr = "";
        }
        $staff = XhhrmStaff::findFirst([
            'conditions' => 'bDelete=0 AND iUserId=:iUserId:',
            'bind'       => ['iUserId' => $userId],
        ]);
        if ($staff) {
            $staff    = $staff->toArray();
            $iPDepId  = end(array_filter(explode(',', $staff['sDepIds'])));
            $sDepName = XhhrmDepart::getDepEnum()[$iPDepId];
        } else {
            $checkStr            = "window.onload = function(){ $('#bt_form_add').hide(); };";
            $staff['sStaffName'] = '账号未绑定';
            $iPDepId             = '';
            $sDepName            = '';
        }

        $custInfo = XhcustInfo::find([
            'columns'    => 'iSchoolId,iCUId,sSchoolName',
            'conditions' => 'bDelete = 0'
        ])->toArray();
        $custInfo = array_column($custInfo, 'sSchoolName', 'iCUId');

        $fixBtn = null;
        $flag   = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId)));
        if ($flag) {
            $fixBtn = '<a id="bt_form_fixData" class="btn-load" style="display: none">保存</a>';
        }
        $leavers = $this->getDepStaffAction(true);
        $this->view->setVars([
            'carInfo'  => $carInfo,
            'userName' => $staff['sStaffName'],
            'iDepId'   => $iPDepId,
            'sDepName' => $sDepName,
            'check'    => $checkStr,
            'cars'     => XHLmCar::getCarEnum(),
            'custInfo' => $custInfo,
            'fixBtn'   => $fixBtn,
            'leavers'  => json_encode($leavers),
        ]);
    }

    /**
     * 车辆管理
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180109
     */
    public function savePrivateAction()
    {
        $id = $this->request->getPost('iUCId', 'string');
        if ($id != "") {
            UserPower::checkUserPower('Lm_Car_UseCarList_Edit') or die('缺少权限');
            $obj = XHLmUseCar::findFirst([
                'conditions' => 'bDelete=0 AND iUCId=:iUCId:',
                'bind'       => ['iUCId' => $id]
            ]);
        } else {
            UserPower::checkUserPower('Lm_Car_UseCarList_Add') or die('缺少权限');
            $obj = new XHLmUseCar();
        }
        $obj->assign($this->request->getPost());
        $userId    = $obj->iCreateUserId ? : Main::getLoginUserInfo('userId');
        $chargeArr = $this->getChargeById($userId, true);
        if (!$id) { //第一次进来
            $obj->iChargeId  = $chargeArr[0];
            $obj->sChargList = '';
        } else {
            if ($obj->iState == 1) {
                if ($obj->iChargeId == Main::getLoginUserInfo('userId')) {
                    if ($obj->sChargList == '' && $obj->iChargeId != end($chargeArr)) { //部门第一次审核
                        $obj->iChargeId  = $chargeArr[1];
                        $obj->sChargList = $chargeArr[0] . ',';
                    } else {
                        foreach ($chargeArr as $index => $value) {
                            if ($value == $obj->iChargeId) {
                                $obj->iChargeId  = $chargeArr[$index + 1];
                                $obj->sChargList .= $chargeArr[$index] . ',';
                                break;
                            }
                        }

                    }
                }
            } elseif ($obj->iState == 3) { //最后一个
                $obj->sChargList .= $obj->iChargeId . ',';
            }
        }

        if ($obj->save()) {
            return $this->sendSuccessResponse('发起申请用车成功');
        } else {
            if ($id) {
                return $this->sendSuccessResponse(500, '发起申请用车失败');
            } else {
                return $this->sendErrorResponse(500, '发起申请用车失败');
            }
        }
    }


    /**
     * 获取私人用车列表
     *
     * create by dale 20180108
     */
    public function privateCarListAction()
    {
        $carPlate = $this->request->getQuery('carPlate', 'string');
        Assets::easyUI();
        Assets::importJs('js/car/privateCarList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('car/privateCarList');
        Template::exists('privateCarList', 'list') or
        die(Main::showMessageModal('privateCarList 配置文件不存在，请先创建！', 109106002));

        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array(
            'type'  => 'button',
            'id'    => 'bt_list_search',
            'text'  => '查找',
            'icon'  => 'fa-search',
            'style' => 'margin-left:10px'
        );
        if (!$carPlate) {
            $this->view->setVars(array(
                'privateCarList' => Template::createList('privateCarList', 'privateCarList', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
//                    'buttonToolbar' => Template::createButtonToolBar($listButton),
                    'field'         => ['sCarOwner', 'sCarPlate', 'sCarType', 'num'],
                ]),
            ));
        } else {
            $this->view->setVars(array(
                'privateCarList' => Template::createList('privateCarList', 'privateCarList', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
//                    'buttonToolbar' => Template::createButtonToolBar($listButton),
                    'field' => [
                        'sApplyName',
                        'sDepName',
                        'sCarOwner',
                        'sCarPlate',
                        'sCarType',
                        'sCarPlate',
                        'mReason',
                        'tStartTime',
                        'tEndTime',
                        'iState',
                        'tLastModifyDate',
                        'iLastModifyUserId'
                    ],
                ]),
            ));
        }
    }

    /**
     * 获取私家车的数据
     *
     * create by dale 20180108
     */
    public function ajaxPrivateCarAction()
    {
        $carOwner = $this->request->getPost('carOwner');
        $useCar   = XHLmUseCar::findFirst([
            'columns'    => 'sCarPlate,sCarType',
            'conditions' => 'iCarId is null AND sCarOwner =:sCarOwner:',
            'bind'       => ['sCarOwner' => $carOwner],
        ]);
        if (!$useCar) {
            return $this->sendErrorResponse(500, '没有找到');
        }

        return $this->sendJsonResponse($useCar->toArray());
    }

    /**
     * 获取私家车数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180108
     */
    public function getPrivateCarAction()
    {
        $carPlate = $this->request->getPost('carPlate', 'string');
        $key      = $this->request->getPost('key', 'string');
        try {
            $sql          = "select * from XHLm_UseCar ";
            $conditions   = [];
            $conditions[] = 'iCarId is null ';
            if ($key) {
                $conditions[] = " sCarType like '%{$key}%' OR sCarOwner like '%{$key}%' ";
            }
            if ($carPlate) {
                $conditions[] = " sCarPlate = '{$carPlate}' ";
            }

            if (count($conditions) > 0) {
                $conditionStr = implode(' AND ', $conditions);
                $conditionStr = "where " . $conditionStr;
            } else {
                $conditionStr = '';
            }
            if (!$carPlate) {
                $conditionStr .= " group by sCarPlate ";
            }
            $sql      .= $conditionStr;
            $data     = Main::runSqlPage(['query' => "select :columns: from ({$sql}) as td ", 'columns' => 'td.*']);
            $enums    = self::$enums;
            $deps     = XhhrmDepart::getDepEnum();
            $sql2     = "select count(iUCId) as num, sCarPlate from XHLm_UseCar WHERE  sCarPlate is not null GROUP BY sCarPlate";
            $carPlate = $this->db->fetchAll($sql2);
            $carPlate = array_column($carPlate, 'num', 'sCarPlate');
            foreach ($data['rows'] as $index => $row) {
                $data['rows'][$index]['iState']   = $enums['iState'][$row['iState']];
                $data['rows'][$index]['sDepName'] = $deps[$row['iDepId']];
                $data['rows'][$index]['num']      = $carPlate[$row['sCarPlate']];
            }
            Main::runUserNameById($data['rows'], ['iLastModifyUserId' => 'iLastModifyUserId'], true);

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * 审批备注列表
     *
     * @param $iUCId
     *
     * @return string
     * create by dale 20180123
     */
    public function descListAction($iUCId)
    {
        if (!$iUCId) {
            return $this->sendViewError('缺少参数');
        }
        $useCar = XHLmUseCar::findFirst($iUCId);
        if (!$useCar) {
            return $this->sendViewError('为找到相应的记录');
        }
        if (!$useCar->mDescJson) {
            return $this->sendViewError('不存在审批意见');
        }
        $arr = json_decode($useCar->mDescJson, true);
        if (count($arr) <= 0) {
            return $this->sendViewError('不存在审批意见');
        }
        $ids       = array_column($arr, 'userId');
        $nameArr   = XhhrmStaff::getStaffNameById($ids);
        $staffInfo = XhhrmStaff::find([
            'columns'    => 'iUserId,sDepIds',
            'conditions' => 'iUserId IN ({idArr:array})',
            'bind'       => ['idArr' => $ids]
        ]);
        $staffInfo = array_column($staffInfo->toArray(), 'sDepIds', 'iUserId');
        foreach ($arr as $index => $value) {
            $arr[$index]['userId']  = '<div title="' . $value['userId'] . '">' . $nameArr[$value['userId']] . '</div>';
            $arr[$index]['depName'] = XhhrmDepart::getDepName($staffInfo[$value['userId']]);
        }
        $this->view->setVars([
            'infos' => $arr,
        ]);
    }

    /**
     * 修复操作
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180123
     */
    public function saveFixDataAction()
    {
        $iUCId        = $this->request->getPost('iUCId', 'int');
        $sDriverName  = $this->request->getPost('sDriverName', 'string');
        $sProvince    = $this->request->getPost('sProvince', 'string');
        $sCity        = $this->request->getPost('sCity', 'string');
        $sCountry     = $this->request->getPost('sCountry', 'string');
        $iSchoolId    = $this->request->getPost('iSchoolId', 'int');
        $mDestination = $this->request->getPost('mDestination', 'string');

        $obj = XHLmUseCar::findFirst($iUCId);

        $obj->sDriverName  = $sDriverName;
        $obj->sProvince    = $sProvince;
        $obj->sCity        = $sCity;
        $obj->sCountry     = $sCountry;
        $obj->iSchoolId    = $iSchoolId;
        $obj->mDestination = $mDestination;
        if ($obj->save()) {
            return $this->sendSuccessResponse('成功');
        } else {
            return $this->sendErrorResponse(500, '失败');
        }
    }
}
